<template>
  <div>
    <h3>角色列表</h3>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="#/welcome">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 简单卡片 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-button type="primary" @click="">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 展示用户列表 -->
      <el-table :data="tableData" stripe border style="width: 100%;margin-top:10px;">
        <!-- 展开列 -->
        <el-table-column type="expand" width="50">
          <template slot-scope="scope">
            <el-row v-bind:class="{bdbottom:true, bdtop:index === 0, vcenter:true}"
              v-for="(item, index) in scope.row.children" :key="item.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row, item.id)" type="success" closable>{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级权限 -->
              <el-col :span="19">
                <el-row v-for="(item2, index2) in item.children"
                  :class="{bdtop:index2 === 0? false: true, vcenter:true}" :key="item2.id">
                  <el-col :span="5">
                    <el-tag @close="removeRightById(scope.row, item2.id)" closable type="info">{{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限  -->
                  <el-col :span="19">
                    <el-tag v-for="(item3, index3) in item2.children" :key="item3.id" type="warning" closable
                      @close="removeRightById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :enterable="false" content="编辑" placement="top">
              <el-button type="primary" size="mini" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :enterable="false" content="删除" placement="top">
              <el-button type="danger" size="mini" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :enterable="false" content="分配权限" placement="top">
              <el-button @click="showSetrightDialog(scope.row)" type="warning" size="mini" icon="el-icon-setting">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[100, 200, 300, 400]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination> -->

      <!-- 分配权限-对话框 -->
      <el-dialog title="分配权限" :visible.sync="centerDialogVisible" width="50%" center>
        <!-- 主体内容--树形控件 -->
        <!-- 
          show-checkbox：复选框
          default-expand-all：默认展开所有的树形控件
          node-key: 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的。选中复选框时对应的id
         -->
        <el-tree ref="treeRef" :data="rightList" default-expand-all show-checkbox node-key="id" :props="treeProps"
          :default-checked-keys="defaultKey">
        </el-tree>
        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="">取 消</el-button>
          <el-button type="primary" @click="allRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 角色列表的所有数据
        tableData: [],
        // 控制对话框的显示和隐藏
        centerDialogVisible: false,
        // 树形控件的所有数据
        rightList: [],
        // 配置那个属性和树形控件的属性绑定
        treeProps: {
          label: 'authName',
          children: 'children'
        },
        // 默认树形控件选中的key
        defaultKey: [],
        // 角色id
        roleId: ''
      }
    },
    created() {
      this.getRoles();
    },
    methods: {
      // 获取所有角色列表
      async getRoles() {
        var {
          data: res
        } = await this.$http.get('/roles');
        console.log('角色列表', res);
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.tableData = res.data;
          return this.$message.success(res.meta.msg);
        }
      },
      // 提示是否要删除对应的权限
      async removeRightById(role, rightId) {
        var confirm = await this.$confirm('此操作将永远删除该权限，是否继续', '提示', {
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        }).catch(err => err)
        if (confirm !== "confirm") {
          return this.$message.info('取消了删除');
        }
        var {
          data: res
        } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        } else {
          role.children = res.data;
          return this.$message.success(res.meta.msg);
        }
      },
      // 展示分配权限的对话框
      async showSetrightDialog(role) {
        // 每次弹出对话框时都保存角色id
        this.roleId = role.id
        if (this.rightList.length !== 0) {
          return this.centerDialogVisible = true
        }
        var {
          data: res
        } = await this.$http.get("/rights/tree")
        console.log("所有权限列表", res)
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.rightList = res.data;
          // 每次打开对话的时候都让默认的key清空。
          this.defaultKey = []
          this.getDefaultKey(role, this.defaultKey)
          // 打开对话框
          this.centerDialogVisible = true
          return this.$message.success(res.meta.msg);
        }
      },
      //  通过递归的形式，获取角色下所有的三级权限的id，并保持到 defaultKey 数组中
      getDefaultKey(node, arr) {
        if (!node.children) {
          return arr.push(node.id);
        }
        node.children.forEach(item => {
          this.getDefaultKey(item, arr);
        });
      },
      // 树形控件--确认按钮
      async allRights() {
        const keys = [
          // ... 表示将数组解构：[1,2,43] ---》 1,2,43
          // getHalfCheckedKeys：返回所有半选中的key组成的数组
          // getCheckedKeys： 返回所有选中的key组成的数组
          ...this.$refs.treeRef.getHalfCheckedKeys(),
          ...this.$refs.treeRef.getCheckedKeys()
        ]
        const keysString = keys.join(",");
        let {
          data: res
        } = await this.$http.post(`roles/${this.roleId}/rights`, {
          rids: keysString
        });
        // 关闭对话框
        this.centerDialogVisible = false
        if (res.meta.status != 200) {
          return this.$message.error(res.meta.msg);
        } else {
          this.getRoles()
          return this.$message.success(res.meta.msg);
        }
      }
    }
  }
</script>

<style>
  .vcenter {
    display: flex;
    align-items: center;
  }

  .el-pagination {
    margin-top: 10px;
  }

  .bdtop,
  .bdbottom {
    border-top: 1px solid #eee;
  }

  .el-tag {
    margin: 7px;
  }

  .box-card {
    width: 100%;
    margin-top: 10px;
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.15);
  }
</style>